/*
 * SlowTreeNodeFactory.java
 * 
 * Written by Joseph Bowbeer and released to the public domain,
 * as explained at http://creativecommons.org/licenses/publicdomain
 */

package jozart.dynamictree;

import javax.swing.tree.DefaultMutableTreeNode;

/**
 * Adds random delays to a TreeNodeFactory.
 *
 * @author  Joseph Bowbeer
 * @version 1.0
 */
public class SlowTreeNodeFactory implements TreeNodeFactory {

    /** Wrapped factory. */
    private final TreeNodeFactory factory;

    /** Maximum delay per child. */
    private final int delay;

    /**
     * Constructs a slow factory.
     * 
     * @param factory wrapped factory 
     * @param delay maximum delay per child in milliseconds
     */
    public SlowTreeNodeFactory(TreeNodeFactory factory, int delay) {
        this.factory = factory;
        this.delay = delay;
    }

    /**
     * Creates children using the wrapped factory and
     * sleeps a random amount per child before returning. 
     */
    public DefaultMutableTreeNode[] createChildren(Object userObject)
            throws Exception {
        DefaultMutableTreeNode[] children = factory.createChildren(userObject);
        // simulate a delay per child
        Thread.sleep((long) (1000 + Math.random() * children.length * delay));
        return children;
    }
}
